package com.course.server.util;

import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import com.course.server.exception.BusinessException;
import com.course.server.exception.BusinessExceptionCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 阿里云发送短信
 */
public class SmsUtil {

    private static final Logger LOG = LoggerFactory.getLogger(SmsUtil.class);
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void sendShortMessage(String accessKeyId,String accessKeySecret,
                                        String signName,String templateCode,
                                        String phoneNumber,String templateParam) throws Exception {

        com.aliyun.dysmsapi20170525.Client client = SmsUtil.createClient(accessKeyId, accessKeySecret);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam(templateParam);
        SendSmsResponse sendSmsResponse;
        // 复制代码运行请自行打印 API 的返回值
        LOG.info("发送短信开始，发送请求："+sendSmsRequest.toString());
        try{
            sendSmsResponse = client.sendSms(sendSmsRequest);
        }catch(Exception e){
            //不知道给空号发短信会不会失败，或者会不会代码这边显示成功，实际上发短信失败
            //不知道什么情况下会抛出Exception
            LOG.warn("发送短信失败，请检查手机号是否正确");
            throw new BusinessException(BusinessExceptionCode.MOBILE_CODE_SEND_FAIL);
        }
        LOG.info("发送短信完成，返回结果："+sendSmsResponse.toString());
    }

    public static void main(String[] args) throws Exception {
        SmsUtil.sendShortMessage("LTAI5tPfsXdx3bL5hduqbuoh",
                "EmGWtLff3G99gcGGj2f7FWhPRcvGqF",
                "Wu的Java小站",/*这个名称必须和审核通过的签名名称一致,否则会在代码这边显示发送成功，实际上发送失败*/
                "SMS_235480142",
                "13369051971",
                /*"{\"code\":\"1234\"}"*/
                "{\"code\":\""+"1111"+"\"}");
    }
}
